package mi.payment.ui.admin;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import mi.payment.BuildConfig;
import mi.payment.R;
import mi.payment.constants.BaseErrorCode;
import mi.payment.controller.BaseQpsSettingController;
import mi.payment.controller.BaseTerminalKeyManagementController;
import mi.payment.controller.QpsSettingController;
import mi.payment.controller.TerminalKeyManagementController;
import mi.payment.ui.base.OneButtonDialog;
import mi.payment.ui.base.ParentActivity;
import mi.payment.utils.Config;
import mi.payment.utils.MToast;
import mi.payment.utils.MustParameterCalibration;
import mi.payment.utils.NetUtils;
import mi.payment.utils.iso8583.ImportRidAndAidParamsUtil;
import mi.payment.utils.transaction.CAPKDownloadTask;
import mi.payment.utils.transaction.CardBinDownloadTask;
import mi.payment.utils.transaction.ICParamsDownloadTask;
import mi.payment.utils.transaction.KEKDownloadTask;
import mi.payment.utils.transaction.MerchantParamsDownloadTask;
import mi.payment.utils.transaction.QpsDownloadTask;
import mi.payment.utils.transaction.TransactionTask;
import sunmi.sunmiui.dialog.EditTextDialog;
import sunmi.sunmiui.title.Title;
import sunmi.sunmiui.utils.LogUtil;

/**
 * 下载管理界面
 *
 * @author lj on 2017/1/7.
 */
public class DownloadManagementActivity extends ParentActivity {

    private EditTextDialog editTextDialog;
    private OneButtonDialog oneButtonDialog;
    private byte flag;
    private BaseQpsSettingController qpsSettingController;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_management);
        qpsSettingController = new QpsSettingController(this);
        initView();
        Config.mPackagePath = getFilesDir().getPath();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        Title title;
        TextView itemRightText;
        title = (Title) findViewById(R.id.download_management_title);
        View icPublicKeyDownload = findViewById(R.id.ic_public_key_download);
        View icParamsDownload = findViewById(R.id.ic_params_download);
        View nonConnectedParametersDownloadView = findViewById(R.id.non_connected_parameters_download);
        View merchantDownloadView = findViewById(R.id.merchant_params_download);
        View kekDownloadView = findViewById(R.id.kek_download);
        View qpsParamDownloadView = findViewById(R.id.qps_params_download);
        View binBDownloadView = findViewById(R.id.bin_b_params_download);
        View binCDownloadView = findViewById(R.id.bin_c_params_download);
        // 激活pos
        View activePosView = findViewById(R.id.item_active_pos);
        switch (BuildConfig.FLAVOR) {
            case "lePos":
                activePosView.setVisibility(View.VISIBLE);
                break;
            default:
                activePosView.setVisibility(View.GONE);
                break;
        }

        kekDownloadView.setVisibility(View.GONE);
        kekDownloadView.setOnClickListener(this);
        icPublicKeyDownload.setOnClickListener(this);
        icParamsDownload.setOnClickListener(this);
        nonConnectedParametersDownloadView.setOnClickListener(this);
        merchantDownloadView.setOnClickListener(this);
        qpsParamDownloadView.setOnClickListener(this);
        binBDownloadView.setOnClickListener(this);
        binCDownloadView.setOnClickListener(this);
        activePosView.setOnClickListener(this);

        TextView icPublicKeyDownloadText = (TextView) icPublicKeyDownload.findViewById(R.id.item_left_text);
        TextView icParamsDownloadText = (TextView) icParamsDownload.findViewById(R.id.item_left_text);
        TextView nonConnectedParametersDownloadText = (TextView) nonConnectedParametersDownloadView.findViewById(R.id.item_left_text);
        TextView merchantDownloadText = (TextView) merchantDownloadView.findViewById(R.id.item_left_text);
        TextView kekDownloadText = (TextView) kekDownloadView.findViewById(R.id.item_left_text);
        TextView qpsDownloadText = (TextView) qpsParamDownloadView.findViewById(R.id.item_left_text);
        TextView binBDownloadText = (TextView) binBDownloadView.findViewById(R.id.item_left_text);
        TextView binCDownloadText = (TextView) binCDownloadView.findViewById(R.id.item_left_text);
        TextView activePosText = (TextView) activePosView.findViewById(R.id.item_left_text);
        activePosText.setText("激活POS设备");

        itemRightText = (TextView) kekDownloadView.findViewById(R.id.item_right_text);
        itemRightText.setVisibility(View.GONE);

        itemRightText = (TextView) icPublicKeyDownload.findViewById(R.id.item_right_text);
        itemRightText.setVisibility(View.GONE);

        itemRightText = (TextView) icParamsDownload.findViewById(R.id.item_right_text);
        itemRightText.setVisibility(View.GONE);

        itemRightText = (TextView) nonConnectedParametersDownloadView.findViewById(R.id.item_right_text);
        itemRightText.setVisibility(View.GONE);

        itemRightText = (TextView) merchantDownloadView.findViewById(R.id.item_right_text);
        itemRightText.setVisibility(View.GONE);

        itemRightText = (TextView) binBDownloadView.findViewById(R.id.item_right_text);
        itemRightText.setVisibility(View.GONE);

        itemRightText = (TextView) binCDownloadView.findViewById(R.id.item_right_text);
        itemRightText.setVisibility(View.GONE);

        itemRightText = (TextView) activePosView.findViewById(R.id.item_right_text);
        itemRightText.setVisibility(View.GONE);

        int color = getResources().getColor(R.color.colorBar);
        String str = getResources().getString(R.string.download_function);
        title.setButtonVisibility(false, true, true, true);
        title.setHeadBgColor(color);
        title.setTitleText(str);
        title.setMenuClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }

        }, null, null, null);

        icPublicKeyDownloadText.setText(getResources().getString(R.string.ic_public_key_download));
        icParamsDownloadText.setText(getResources().getString(R.string.ic_params_download));
        nonConnectedParametersDownloadText.setText(getResources().getString(R.string.non_connected_parameters_download));
        merchantDownloadText.setText(getResources().getString(R.string.terminal_params_download));
        kekDownloadText.setText(getString(R.string.kek_download));
        qpsDownloadText.setText(getResources().getString(R.string.downloadQpsParam));
        binBDownloadText.setText(getResources().getString(R.string.downloadBin_B));
        binCDownloadText.setText(getResources().getString(R.string.downloadBin_C));

        if (!qpsSettingController.showNoParameterDownload()) { // 隐藏非接参数下载,集成按钮
            nonConnectedParametersDownloadView.setVisibility(View.GONE);
        }

        if (!qpsSettingController.shownQPSParam()) {
            qpsParamDownloadView.setVisibility(View.GONE);
        }

        if (!qpsSettingController.showBinB_Button()) {
            binBDownloadView.setVisibility(View.GONE);
        }
        if (!qpsSettingController.showBinC_Button()) {
            binCDownloadView.setVisibility(View.GONE);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (oneButtonDialog != null) {
            oneButtonDialog.dismiss();
            oneButtonDialog = null;
        }
        if (editTextDialog != null) {
            editTextDialog.dismiss();
            editTextDialog = null;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.kek_download:
                // KEK下载
                if (MustParameterCalibration.canToNext2()) {
                    downloadKEK();
                } else {
                    MToast.showToast(getString(R.string.system_errorcode), Toast.LENGTH_LONG);
                }
                break;
            case R.id.ic_public_key_download:
                // 公钥下载(CAP K)
                if (MustParameterCalibration.canToNext()) {
                    publicKeyDownload();
                } else {
                    MToast.showToast(getString(R.string.system_errorcode), Toast.LENGTH_LONG);
                }
                break;
            case R.id.ic_params_download:
                // IC卡参数下载(AID)
                if (MustParameterCalibration.canToNext()) {
                    ICParametersDownload();
                } else {
                    MToast.showToast(getString(R.string.system_errorcode), Toast.LENGTH_LONG);
                }
                break;

            case R.id.non_connected_parameters_download:
                // 非接参数下载和卡BIN下载
                if (MustParameterCalibration.canToNext()) {
                    QpsDownload();
                    BinDownload();
                } else {
                    MToast.showToast(getString(R.string.parames_error), Toast.LENGTH_LONG);
                }
                break;
            case R.id.merchant_params_download:
                // 终端参数下载
                boolean canToNext = mSupportController.isDownloadMerParams();
                if (canToNext) {
                    merchantParametersDownload();
                } else {
                    MToast.showToast(getString(R.string.parames_error), Toast.LENGTH_LONG);
                }

                break;

            case R.id.qps_params_download:
                //非接业务参数下载（开关）
                if (MustParameterCalibration.canToNext()) {
                    qpsParamDownload();
                } else {
                    MToast.showToast(getString(R.string.parames_error), Toast.LENGTH_LONG);
                }
                break;

            case R.id.bin_b_params_download:
                // BIN B 表下载
                if (MustParameterCalibration.canToNext()) {
                    BinBDownload(false);
                } else {
                    MToast.showToast(getString(R.string.parames_error), Toast.LENGTH_LONG);
                }
                break;
            case R.id.bin_c_params_download:
                // BIN C 表下载
                if (MustParameterCalibration.canToNext()) {
                    BinCDownload(false);
                } else {
                    MToast.showToast(getString(R.string.parames_error), Toast.LENGTH_LONG);
                }
                break;
            case R.id.item_active_pos:
                BaseTerminalKeyManagementController controller = new TerminalKeyManagementController(this);
                controller.downloadTMK();
                break;
            default:
                break;
        }
    }

    private void showDialog() {
        oneButtonDialog = OneButtonDialog.createOneButtonDialog(this);
        oneButtonDialog.setClickAble(false);
        oneButtonDialog.show();
    }

    private void downloadKEK() {
        if (!NetUtils.isNetworkConnected(getApplicationContext())) {
            showToast(getString(R.string.download_nonet));
            return;
        }
        KEKDownloadTask task = new KEKDownloadTask(this) {
            @Override
            protected void onPreExecuteImpl() {
                showDialog();
            }

            @Override
            protected void onPostExecuteImpl(String ret) {
                oneButtonDialog.setClickAble(true);
                if (TextUtils.equals("00", ret)) {
                    oneButtonDialog.setMsg(getString(R.string.download_success));
                } else if (TextUtils.equals("-1", ret)) {
                    oneButtonDialog.setMsg(getString(R.string.download_failed));
                } else {
                    oneButtonDialog.setMsg(BaseErrorCode.getCode(ret));
                }
            }

        };
        task.execute();
        startTimeoutTimer(task);
    }

    /**
     * RID下载
     */
    private void publicKeyDownload() {
        if (!NetUtils.isNetworkConnected(getApplicationContext())) {
            showToast(getString(R.string.download_nonet));
            return;
        }
        CAPKDownloadTask task = new CAPKDownloadTask(getApplicationContext()) {

            @Override
            protected void onPreExecuteImpl() {
                showDialog();
            }

            @Override
            protected void onPostExecuteImpl(String ret) {
                oneButtonDialog.setClickAble(true);
                if (TextUtils.equals("FF", ret)) {
                    oneButtonDialog.setMsg(getString(R.string.download_failed));
                } else if (TextUtils.equals("NE", ret)) {
                    oneButtonDialog.setMsg(getString(R.string.download_nonet));
                } else {
                    ImportRidAndAidParamsUtil.setRIDs();
                    oneButtonDialog.setMsg(getString(R.string.download_success));
                }
            }

        };
        task.execute();
        startTimeoutTimer(task);
    }

    // AID参数下载
    public void ICParametersDownload() {
        if (!NetUtils.isNetworkConnected(getApplicationContext())) {
            showToast(getString(R.string.download_nonet));
            return;
        }
        ICParamsDownloadTask task = new ICParamsDownloadTask(getApplicationContext()) {

            @Override
            protected void onPreExecuteImpl() {
                showDialog();
            }

            @Override
            protected void onPostExecuteImpl(String ret) {
                oneButtonDialog.setClickAble(true);
                if (TextUtils.equals("FF", ret)) {
                    oneButtonDialog.setMsg(getString(R.string.download_failed));
                } else if (TextUtils.equals("NE", ret)) {
                    oneButtonDialog.setMsg(getString(R.string.download_nonet));
                } else {
                    ImportRidAndAidParamsUtil.setAIDs();
                    oneButtonDialog.setMsg(getString(R.string.download_success));
                }
            }

        };
        task.execute();
        startTimeoutTimer(task);
    }

    /**
     * 终端参数下载
     */
    private void merchantParametersDownload() {
        if (!NetUtils.isNetworkConnected(getApplicationContext())) {
            showToast(getString(R.string.download_nonet));
            return;
        }
        MerchantParamsDownloadTask task = new MerchantParamsDownloadTask(this) {
            @Override
            protected void onPreExecuteImpl() {
                showDialog();
            }

            @Override
            protected void onPostExecuteImpl(String ret) {
                oneButtonDialog.setClickAble(true);
                if (TextUtils.equals("00", ret)) {
                    oneButtonDialog.setMsg(getString(R.string.download_success));
                } else if (TextUtils.equals("NE", ret)) {
                    oneButtonDialog.setMsg(getString(R.string.download_nonet));
                } else {
                    oneButtonDialog.setMsg(getString(R.string.download_failed) + ": " + BaseErrorCode.getCode(ret));
                }
            }

        };
        task.execute();
        startTimeoutTimer(task);
    }

    private void startTimeoutTimer(TransactionTask task) {
        task.setTimeoutTask(new Runnable() {
            @Override
            public void run() {
                oneButtonDialog.setClickAble(true);
                oneButtonDialog.setMsg(getString(R.string.download_failed) + ": " + BaseErrorCode.getCode("68"));
            }
        });
    }

    // 非接业务参数下载,集成按钮
    public void QpsDownload() {
        if (!NetUtils.isNetworkConnected(getApplicationContext())) {
            showToast(getString(R.string.download_nonet));
            return;
        }
        QpsDownloadTask task = new QpsDownloadTask(getApplicationContext()) {
            @Override
            protected void onPreExecuteImpl() {
                showDialog();
            }

            @Override
            protected void onPostExecuteImpl(String ret) {
                LogUtil.e("DownloadManagementActivity", "DownloadManagementActivity-QpsDownload-onPostExecute-ret=" + ret);
                if (TextUtils.equals("00", ret)) {
                    flag |= 1;
                }
            }
        };
        task.execute();
        startTimeoutTimer(task);
    }

    /**
     * 卡BIN下载
     */
    private void BinDownload() {
        BinBDownload(true);
        BinCDownload(true);
    }

    //非接业务参数开关下载
    private void qpsParamDownload() {
        if (!NetUtils.isNetworkConnected(getApplicationContext())) {
            showToast(getString(R.string.download_nonet));
            return;
        }
        QpsDownloadTask qpsDownloadTask = new QpsDownloadTask(getApplication()) {
            @Override
            protected void onPreExecuteImpl() {
                showDialog();
            }

            @Override
            protected void onPostExecuteImpl(String ret) {
                oneButtonDialog.setClickAble(true);
                if (TextUtils.equals("00", ret)) {
                    oneButtonDialog.setMsg(getString(R.string.download_success));
                } else if (TextUtils.equals("NE", ret)) {
                    oneButtonDialog.setMsg(getString(R.string.download_nonet));
                } else {
                    oneButtonDialog.setMsg(getString(R.string.download_failed) + ": " + BaseErrorCode.getCode(ret));
                }
            }
        };
        qpsDownloadTask.execute();
        startTimeoutTimer(qpsDownloadTask);

    }


    private void BinBDownload(final boolean isMulti) {
        if (!NetUtils.isNetworkConnected(getApplicationContext())) {
            showToast(getString(R.string.download_nonet));
            return;
        }

        CardBinDownloadTask taskB = new CardBinDownloadTask(getApplicationContext()) {

            @Override
            protected void onPreExecuteImpl() {
                if (!isMulti) {
                    showDialog();
                }
            }

            @Override
            protected void onPostExecuteImpl(String s) {
                if (isMulti) {
                    syncMultiTask(s, "BinB");
                } else {
                    syncSingleTask(s);
                }

            }
        };
        taskB.initBinBParams();//下载卡BINB
        startTimeoutTimer(taskB);
        taskB.execute();

    }

    private void BinCDownload(final boolean isMulti) {
        if (!NetUtils.isNetworkConnected(getApplicationContext())) {
            showToast(getString(R.string.download_nonet));
            return;
        }
        CardBinDownloadTask taskC = new CardBinDownloadTask(getApplicationContext()) {

            @Override
            protected void onPreExecuteImpl() {
                if (!isMulti) {
                    showDialog();
                }
            }

            @Override
            protected void onPostExecuteImpl(String s) {
                if (isMulti) {
                    syncMultiTask(s, "BinC");
                } else {
                    syncSingleTask(s);
                }
            }
        };
        taskC.initBinCParams();//下载卡BINC;
        startTimeoutTimer(taskC);
        taskC.execute();
    }


    private void syncMultiTask(String s, String type) {
        if (type.equals("BinB")) {
            if (s.equals("00")) {
                flag |= 1 << 1;
            }
        } else if (type.equals("BinC")) {
            if (s.equals("00")) {
                if (flag == 0x03) {
                    oneButtonDialog.setClickAble(true);
                    oneButtonDialog.setMsg(getString(R.string.download_success));
                } else {
                    oneButtonDialog.setClickAble(true);
                    oneButtonDialog.setMsg(getString(R.string.download_failed));
                }
            } else {
                oneButtonDialog.setClickAble(true);
                oneButtonDialog.setMsg(getString(R.string.download_failed));
            }
        } else {
            return;
        }
    }

    private void syncSingleTask(String s) {
        if (s.equals("00")) {
            oneButtonDialog.setClickAble(true);
            oneButtonDialog.setMsg(getString(R.string.download_success));
        } else {
            oneButtonDialog.setClickAble(true);
            oneButtonDialog.setMsg(getString(R.string.download_failed));
        }
    }


}
